﻿/*  
 *  IIS LogFile Analyser, Copyright (C) 2013. http://www.iis-analyser.com
 *  --
 *  This program is free software, provided "AS IS" WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
 * 
 *  File Author: Ian Quigley,    2013-02-23
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataStore
{
    public class Schema
    {
        public static IEnumerable<TableDefinition> Get
        {
            get
            {
                foreach (var type in typeof(Schema).Assembly.GetTypes())
                {
                    var table = type.GetCustomAttributes(typeof(TableNameAttribute), true);
                    if (table.Length == 1)
                        yield return new TableDefinition() { Table = (TableNameAttribute)table[0], Fields = GetFieldDescriptions(type) };

                }
            }
        }

        private static List<FieldDescriptionAttribute> GetFieldDescriptions(Type type)
        {
            List<FieldDescriptionAttribute> list = new List<FieldDescriptionAttribute>();
            foreach (var pi in type.GetProperties())
            {
                var attrib = pi.GetCustomAttributes(typeof(FieldDescriptionAttribute), true);
                if (attrib == null || attrib.Length != 1)
                    continue;

                list.Add((FieldDescriptionAttribute)attrib[0]);
            }

            foreach (var fi in type.GetFields())
            {
                var attrib = fi.GetCustomAttributes(typeof(FieldDescriptionAttribute), true);
                if (attrib == null || attrib.Length != 1)
                    continue;

                list.Add((FieldDescriptionAttribute)attrib[0]);
            }

            return list;
        }

    }

    public class TableDefinition
    {
        public TableNameAttribute Table;
        public List<FieldDescriptionAttribute> Fields;
    }

    public class TableNameAttribute : System.Attribute
    {
        public TableNameAttribute(string name)
        {
            Name = name;
        }

        public string Name;
    }

    public class FieldDescriptionAttribute : System.Attribute
    {
        public FieldDescriptionAttribute(string sqlColumnName, string description)
        {
            SqlColumnName = sqlColumnName;
            Description = description;
        }

        public string SqlColumnName;
        public string Description;
    }
}
